package com.dd.cloud.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.dd.cloud.user.service.phar.pharservice.HrPharService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@Validated
@RestController
@RequestMapping("/test/hr")
@Slf4j
public class TestController {

    @Autowired
    private HrPharService pharService;

    @GetMapping("/token")
    public ResponseEntity<String> getToken() throws IOException {
        // 设置公众号的 AppID 和 AppSecret
        String appId = "wx4b5b31862521d9d0";
        String appSecret = "91c429ef32a63f6ce64a20502efc6d8d";

        // 构造请求URL
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        Response response = client.newCall(request).execute();
        JSONObject jsonResponse = JSONObject.parseObject(response.body().string());
        System.out.println("token返回:" + jsonResponse);
        String accessToken = jsonResponse.getString("access_token");

        // 构造消息内容
        JSONObject articleJson = new JSONObject();
        articleJson.put("touser", "otUYV53764M0-b854mUtvAFc2O8s"); // 将 openid1 和 openid2 替换为目标用户的 OpenID
        articleJson.put("msgtype", "text");
        JSONObject textContent = new JSONObject();
        textContent.put("content", "这里是要发送的文章内容");
        articleJson.put("text", textContent);

        // 发送消息
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        okhttp3.RequestBody body = RequestBody.create(mediaType, articleJson.toJSONString());
        Request sendRequest = new Request.Builder()
                .url("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken)
                .post(body)
                .build();
        Response sendResponse = client.newCall(sendRequest).execute();
        System.out.println(sendResponse.body().string());
//        log.info("=====获取token========");
//        String token = pharService.getToken();
        return ResponseEntity.ok(sendResponse.body().string());
    }
}
